import { Text, View } from '@tarojs/components';
import theme from '@/theme';
import { ComponentProps, useMemo, useState } from 'react';
import './index.scss';
import classNames from 'classnames';
import { Icon, Space } from 'pd-taro-ui';

interface RadioGroupProps {
  placeholder?: string;
  value?: string | number;
  onChange?: (value: string | number) => void;
  onBlur?: any;
  staticed?: boolean;
  disabled?: boolean;
  compProps?: any;
  /** 渲染标签：默认label */
  labelField?: string;
  /** 渲染值：默认value */
  valueField?: string;
  /** 是否显示为一行，默认true */
  inline?: boolean;
  options?: { label: any; value: any; [key: string]: any }[];
}
const RadioGroup = ({
  onChange,
  value,
  disabled,
  staticed,
  onBlur,
  placeholder,
  compProps,
  options = [],
  inline = true,
  labelField = 'label',
  valueField = 'value',
}: RadioGroupProps) => {
  const setCheck = (item: any) => {
    if (disabled) {
      return;
    }
    const val = item[valueField];
    onChange?.(val);
  };
  const getIsCheck = (item: any) => {
    const val = item[valueField];
    return val === value;
  };

  const staticStr = useMemo(() => {
    return options.find(option => option[valueField] === value)?.[labelField] || '';
  }, [value, options, labelField, valueField]);

  if (staticed) {
    return <View className='pd-radioGroup--static'>{staticStr}</View>;
  }
  return (
    <View className={classNames({ 'pd-radioGroup': true, 'pd-radioGroup--disabled': disabled })}>
      <Space row={inline} items={inline ? 'center' : 'stretch'} wrap={true}>
        {options.map((item, index) => {
          const checked = getIsCheck(item);
          return (
            <Space key={index} row items='center' gap={8} onClick={() => setCheck(item)}>
              <Icon name={checked ? 'circle_selected' : 'unselected'} color={checked ? theme.primaryColor : '#bbb'} />
              {!!item[labelField] && <Text className='pd-radioGroup__label'>{item[labelField]}</Text>}
            </Space>
          );
        })}
      </Space>
    </View>
  );
};
export default RadioGroup;
